import { Injectable, NgZone } from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class InterfaceService {


  apiBase = "http://localhost:9000/gateway/ai";

  constructor(private http: HttpClient, private ngZone: NgZone) { }

  sseEmitterClick(){
    const url = this.apiBase + "/test/sse4";
    return this.getObservable(url);
  }

  directorSseEmitterClick(){
    const url = this.apiBase + "/test/sse2";
    return this.getObservable(url);
  }

  webClientDirectorSseEmitterClick(){
    const url = this.apiBase + "/test/sse3";
    return this.getObservable(url);
  }

  getObservable(url:String){
    return new Observable(observer => {
      // @ts-ignore
      const eventSource = new EventSource(url);

      // 监听 message 事件（默认事件类型）
      eventSource.onmessage = (event) =>{
        this.ngZone.run(() => {
          try{
            // 解析 JSON 数据（假设服务端返回 JSON 字符串）
            const data = JSON.parse(event.data);
            observer.next(data);
          }catch (e) {
            observer.error("数据解析失败: " + e);
          }
        })
      }

      // 监听自定义事件类型（如 event: custom）
      eventSource.addEventListener('custom', (event: MessageEvent) => {
        this.ngZone.run(() => {
          observer.next({ type: 'custom', data: event.data });
        });
      });

      // 错误处理
      eventSource.onerror = (error) => {
        this.ngZone.run(() => {
          observer.error(error);
          eventSource.close();
        });
      };

      // 关闭连接时的清理逻辑
      return () => {
        eventSource.close();
      };
    })
  }
}
